﻿using NewfarTormentTool.core;
using NewfarTormentTool.data;
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace NewfarTormentTool.sub
{
    /// <summary>
    /// 存储用户记录子面板
    /// </summary>
    public partial class SaveUser : Form
    {
        public SaveUser()
        {
            InitializeComponent();
            Label_ErrorTips.Visible = false;
            Label_ErrorTips.BindingContextChanged += new EventHandler(Label_ErrorTips_Changed);
        }

        /// <summary>
        /// 重设报错标签位置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Label_ErrorTips_Changed(object sender, EventArgs e)
        {
            int x = Width - Label_ErrorTips.Width - 30;
            Label_ErrorTips.Location = new Point(x, Label_ErrorTips.Location.Y);
        }

        /// <summary>
        /// 主面板
        /// </summary>
        private MainForm Main;

        /// <summary>
        /// 设置主面板
        /// </summary>
        public void SetMain(MainForm mf)
        {
            Main = mf;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Save_Click(object sender, EventArgs e)
        {
            string user = TB_User.Text;
            if (string.IsNullOrEmpty(user) || "$".Equals(user))
            {
                Label_ErrorTips.Text = "请输入正确的用户名!";
                Label_ErrorTips.Visible = true;
                return;
            }
            if (RoleDataStorage.Instance.Records.ContainsKey(user))
            {
                if (MessageBox.Show("该用户已存在,是否覆盖记录?", "Warn", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                {
                    return;
                }
            }
            UserRecord record = new UserRecord();
            record.user = user;
            record.actives = RoleDataStorage.Instance.UserRoles.Values.Where(r => r.Active).Select(r => r.Config.id).ToList();
            RoleDataStorage.Instance.AddOrUpdateRecord(user, record);
            // 指定新的当前用户
            RoleDataStorage.Instance.CurUser = user;
            // 主面板刷新
            Main.RefreshCombo();
            Main.RefreshSaveButton();
            // 移除自己
            Close();
        }
    }
}
